package ntd.util.frame.msg.service.handle.jpush.push;

import cn.hutool.core.util.StrUtil;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import ntd.util.config.common.exception.ComException;
import ntd.util.frame.msg.MsgHandle;
import ntd.util.frame.msg.bo.MsgInBO;
import ntd.util.frame.msg.bo.MsgInfo;
import ntd.util.frame.msg.service.context.MsgContext;

import static ntd.util.frame.msg.service.handle.jpush.util.UtilJPush.transform;

public class JPushMsgHandle implements MsgHandle {

    @Override
    public Boolean handle(MsgContext msgContext) {
        if (msgContext.getAction().equals("sendMsg")) {
            return sendMsg(msgContext);
        }
        return false;
    }

    private Boolean sendMsg(MsgContext msgContext) {
        JPushHelper jPushHelper = new JPushHelper(transform(msgContext));

        jPushHelper.sendMsg(buildMsgInfo(msgContext));

        return Boolean.TRUE;
    }

    private JPushHelper.JPushMsgInBO buildMsgInfo(MsgContext param) {
        MsgInBO msgInBO = param.getMsgInBO();
        String receiverIds = msgInBO.getReceiverIds();
        String receiverTags = msgInBO.getReceiverTags();
        String receiverAlias = msgInBO.getReceiverAlias();
        if (StrUtil.isBlank(receiverIds) && StrUtil.isBlank(receiverTags) && StrUtil.isBlank(receiverAlias)) {
            throw new ComException("接收人不能为空!");
        }
        Audience audience = Audience.all();
        if (StrUtil.isNotBlank(receiverIds) && !receiverIds.equals("-1")) {
            audience = Audience.registrationId(StrUtil.split(receiverIds, ","));
        }
        if (StrUtil.isNotBlank(receiverTags)) {
            audience = Audience.tag(StrUtil.split(receiverTags, ","));
        }
        if (StrUtil.isNotBlank(receiverAlias)) {
            audience = Audience.alias(StrUtil.split(receiverAlias, ","));
        }
        JPushHelper.JPushMsgInBO jPushMsgInBO = new JPushHelper.JPushMsgInBO();
        jPushMsgInBO.setPlatform(Platform.android());
        jPushMsgInBO.setAudience(audience);

        MsgInfo msgInfo = msgInBO.getMsgInfo();

        jPushMsgInBO.setNotification(Notification.android(msgInfo.getContent(), msgInfo.getTitle(), msgInfo.getExtras()));

        return jPushMsgInBO;
    }
}
